﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Talentnet.Data.Access;
using Talentnet.Core.Utilities.Mail;
using Talentnet.Core.Utilities;
using Talentnet.Core.Utilities.Cryptophy;

public partial class freeaccess_ActiveAccount : NormalPage
{
    private const int TimeToExpireHours = 72;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsStaticQueryString && SecureQueryString["k"] != null)
        {
            string key = SecureQueryString["k"];

            //Step1: Check valid key
            SEC_User user = DatabaseManager.TalentnetDB.SEC_Users.SingleOrDefault(u => u.UserPassword == key);
            
            if (user != null)
            {
                if (user.UserPasswordDTS.Value.AddHours(TimeToExpireHours) > DateTime.Now)
                {
                    //Step 2: Gen password
                    string tempPwd = Common.GenPwd();
                    user.UserPassword = CryptoAgent.Current.MD5(tempPwd);
                    user.UserPasswordType = (int)SiteEnums.PasswordType.SysPwd;
                    user.UserPasswordDTS = DateTime.Now;
                    user.Status = (byte)SiteEnums.UserStatus.Active;
                    DatabaseManager.TalentnetDB.SubmitChanges();

                    //Step3: Send Email
                    string fromEmail = SessionManager.MailSetting.EmailContact;
                    //Load mail template
                    System.IO.StreamReader mailTemplate = new System.IO.StreamReader(MapPath(@"~\App_Data\EmailTemplates\GenPwd.htm"));
                    string mail_body = mailTemplate.ReadToEnd();
                    string subject = "[Talentnet] - New Password Notification";
                    mailTemplate.Close();
                    mail_body = mail_body.Replace("[password]", tempPwd);
                    MailServices.SendEmail(fromEmail, user.Email, subject, mail_body, SessionManager.MailSetting);
                    ctrlMsg.Text = LoadText("Common", "ActiveAccountSuccess");
                }
                
            }
            else
            {
                ctrlMsg.Text = LoadText("Common", "ActiveAccountFail");
            }
        }
        else
        {
            ctrlMsg.Text = LoadText("Common", "ActiveAccountFail");
        }
    }
}
